#include "codecs.h"

Codecs::Codecs(QWidget * parent) : QDialog(parent)
{
codecsComboBox = new ComboBox;
setupUi(this);
hboxLayout->addWidget(codecsComboBox);

find_codecs();
QObject::connect( codecsComboBox,
                  SIGNAL( activated(int) ),
                  this,
                  SLOT( update_textEdit() ) );
QObject::connect( fileToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( open_file() ) );

}

void Codecs::set_encoded( const QByteArray & data )
{
encoded_data = data;
update_textEdit();
}

void Codecs::update_textEdit()
{
int mib = codecsComboBox->itemData( codecsComboBox->currentIndex() ).toInt();
QTextCodec * codec = QTextCodec::codecForMib(mib);

QTextStream in( &encoded_data );
in.setAutoDetectUnicode(false);
in.setCodec(codec);
decoded_data = in.readAll();

textEdit->setPlainText(decoded_data);
}

void Codecs::open_file()
{
QString fileName = QFileDialog::getOpenFileName( this,
                                                 tr("Select file"),
                                                 QLatin1String(""),
                                                 tr("All Files (*);;Text Files (*.txt);;HTML Files (*.html *.htm)") );
    if ( true == fileName.isEmpty() )
    {
    return;
    }

QFile file(fileName);

    if ( true != file.open(QFile::ReadOnly | QFile::Text) )
    {
    QMessageBox::warning( this,
                          tr("Codecs"),
                          tr("Cannot read file %1:\n%2")
                             .arg(fileName)
                             .arg(file.errorString()));
    return;
    }

QByteArray data = file.readAll();
set_encoded(data);
}

void Codecs::find_codecs()
{
codecs.clear();
QMap<QString, QTextCodec *> codecMap;
QRegExp iso8859RegExp("ISO[- ]8859-([0-9]+).*");

    foreach ( int mib, QTextCodec::availableMibs() )
    {
    QTextCodec * codec = QTextCodec::codecForMib(mib);

    QString sortKey = codec->name().toUpper();
    int r;

        if ( sortKey == QLatin1String("SYSTEM") )
        {
        r = 1;
        }
        else if ( sortKey.startsWith("UTF-8") )
        {
        r = 2;
        }
        else if ( sortKey.startsWith("UTF-16") )
        {
        r = 3;
        }
        else if ( sortKey.startsWith("KOI8") )
        {
        r = 4;
        }
        else if ( iso8859RegExp.exactMatch(sortKey) )
        {
            if ( iso8859RegExp.cap(1).size() == 1 )
            {
            r = 5;
            }
            else
            {
            r = 6;
            }
        }
        else
        {
        r = 7;
        }
    sortKey.prepend(QChar('0' + r));
    codecMap.insert(sortKey, codec);
    }

codecs = codecMap.values();

codecsComboBox->clear();
    foreach (QTextCodec * codec, codecs)
    {
    codecsComboBox->addItem( codec->name(), codec->mibEnum() );
    }

}

